package com.compty.paint.web.member;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import com.compty.core.framework.context.spring.SpringContextHolder;
import com.compty.core.framework.util.MailUtil;
import com.compty.core.framework.util.StringUtil;
import com.compty.core.page.Page;
import com.compty.core.struts2.BaseAction;
import com.compty.core.utils.CommonsUtil;
import com.compty.paint.domain.CityInfo;
import com.compty.paint.domain.LogInfo;
import com.compty.paint.domain.Painting;
import com.compty.paint.domain.ProvinceInfo;
import com.compty.paint.domain.support.LogTypeEnum;
import com.compty.paint.manager.CityInfoManager;
import com.compty.paint.manager.LogInfoManager;
import com.compty.paint.manager.PaintingManager;
import com.compty.paint.manager.ProvinceInfoManager;
import com.compty.paint.manager.UserStateManager;
import com.compty.paint.util.Constants;
import com.compty.security.domain.Menu;
import com.compty.security.domain.Role;
import com.compty.security.domain.User;
import com.compty.security.domain.UserState;
import com.compty.security.manager.MenuManager;
import com.compty.security.manager.RoleManager;
import com.compty.security.manager.UserManager;

/**
 * 会员注册
 * @author zhuqh
 */
public class MemberAction extends BaseAction<User> {

	private static final long serialVersionUID = 5992258831212551240L;
	
	private LogInfoManager logInfoManager;
	private transient UserManager userManager = null;
	private transient MenuManager menuManager = null;
	private transient UserStateManager userStateManager;
	private transient ProvinceInfoManager provinceInfoManager;
	private transient CityInfoManager cityInfoManager;
	private transient RoleManager roleManager;
	
	private User userInfo;

	public User getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(User userInfo) {
		this.userInfo = userInfo;
	}

	public void setUserStateManager(UserStateManager userStateManager) {
		this.userStateManager = userStateManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public void setProvinceInfoManager(ProvinceInfoManager provinceInfoManager) {
		this.provinceInfoManager = provinceInfoManager;
	}

	public void setCityInfoManager(CityInfoManager cityInfoManager) {
		this.cityInfoManager = cityInfoManager;
	}
	
	public void setLogInfoManager(LogInfoManager logInfoManager) {
		this.logInfoManager = logInfoManager;
	}

	public void setMenuManager(MenuManager menuManager) {
		this.menuManager = menuManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	/**
	 * 注册(第一步)
	 */
	public String register(){
		
		if(userInfo!=null){
			String username = userInfo.getUsername();
			
			List<User>  userlist= userManager.findBy("username", username);
			if(userlist!=null && userlist.size()>0)
			{
				addFieldError("username", "该用户名已被注册");
				return INPUT;
			}
			
			if(Constants.Auto_Audit){
				UserState userState = userStateManager.findUniqueBy("english_name",Constants.User_State_Normal); //设置用户初始状态审核通过，正常
				userInfo.setUserState(userState);
			}else{
				UserState userState = userStateManager.findUniqueBy("english_name",Constants.User_State_Init); //设置用户初始状态为待审
				userInfo.setUserState(userState);
			}
			
			String pwd_repeat = userInfo.getPassword();
			userInfo.setPassword(CommonsUtil.getMD5(pwd_repeat)); //将密码用md5加密
			userInfo.setRegisterTime(Calendar.getInstance().getTime());
			
			userInfo.setAdministratorFlag("0"); //非管理员账户
			
			String user_role = request.getParameter("user_role");
			Long role_id = Long.valueOf(user_role);
			Role role = roleManager.get(role_id);
			userInfo.getRoles().add(role);
			
			session.setAttribute(Constants.RegisterInformation, userInfo);
			session.setAttribute(Constants.PassWord_Original, pwd_repeat);
			
			List<ProvinceInfo> provinceInfoList = provinceInfoManager.getAll();
			request.setAttribute("provinceInfoList", provinceInfoList);
			
			return "additional_register";
		}
		
		return INPUT;
	}
	
	/**
	 * 注册第二步，补充会员资料,完成注册
	 */
	public String completeRegister(){
		
		String companyName = request.getParameter("companyName");
		String userType = request.getParameter("userType");
		String yyzh = request.getParameter("yyzh");
		String idCard = request.getParameter("idCard");
		String address = request.getParameter("address");
		String zipCode = request.getParameter("zipCode");
		String contact = request.getParameter("contact");
		String tel = request.getParameter("tel");
		String emailAddress = request.getParameter("emailAddress");
		String account = request.getParameter("account");
		String bank = request.getParameter("bank");
		String account_number = request.getParameter("account_number");
		String provinceInfo = request.getParameter("province");
		String cityInfo = request.getParameter("city");
		
		if( session.getAttribute(Constants.RegisterInformation) != null ){
			
			User user = (User) session.getAttribute(Constants.RegisterInformation);
			user.setCompanyName(companyName);
			user.setUserType(userType);
			user.setYyzh(yyzh);
			user.setIdCard(idCard);
			user.setAddress(address);
			user.setZipCode(zipCode);
			user.setContact(contact);
			user.setTel(tel);
			user.setEmailAddress(emailAddress);
			user.setAccount(account);
			user.setBank(bank);
			user.setAccount_number(account_number);
			
			if( provinceInfo != null ){
				if(StringUtil.isDigit(provinceInfo)){
					ProvinceInfo p = provinceInfoManager.get(Long.valueOf(provinceInfo));
					user.setProvinceInfo(p);
				}
			}
			
			if(cityInfo != null ){
				if(StringUtil.isDigit(cityInfo)){
					CityInfo  c = cityInfoManager.get(Long.valueOf(cityInfo));
					user.setCityInfo(c);
				}
			}
			
			userManager.save(user);
			
			/************ 发送邮件通知 begin *****************/
			if(StringUtil.validEmail(emailAddress)){
				String orginalPwd = (String)session.getAttribute(Constants.PassWord_Original);
				String title = "欢迎成为可观艺术网会员";
				String content = "尊敬的用户您已成功注册为可观艺术网商户会员，您的登录账号是"+user.getUsername()+"， 密码是"+orginalPwd+"。请妥善保管";
				MailUtil.sendTextMail(emailAddress, title, content);
			}
			/************ 发送邮件通知 end *****************/
		}
	
		return "completeRegister";
	}
	
	/**
	 * 查询登录用户信息
	 */
	public String findUser(){
		
		User user = (User) session.getAttribute(Constants.Userinfo);
		
		if (user != null) {
			Long id = user.getId();
			this.userInfo  = userManager.get(id);
			
			List<ProvinceInfo> provinceInfoList = provinceInfoManager.getAll();
			request.setAttribute("provinceInfoList", provinceInfoList);
			
		}
		
		return SUCCESS;
	}
	
	/**
	 * 修改会员基本资料
	 */
	public String modify() {
		if(this.userInfo != null){
    		User  user = userManager.get(userInfo.getId());
    		
    		user.setUsername(userInfo.getUsername());
    		user.setMobile(userInfo.getMobile());
    		user.setTelphone(userInfo.getTelphone());
    		user.setEmailAddress(userInfo.getEmailAddress());
    		user.setAddress(userInfo.getAddress());
    		
    		userManager.save(user);
    		
    		this.userInfo = user;
    	}
		return SUCCESS;
	}
	
	/**
	 * 
	 *@Todo:修改密码
	 *@CreateTime:2011-10-11 下午01:21:59
	 * @return
	 */
	public String changePassword(){
		
		if(this.userInfo != null){
			
    		User  user = userManager.get(userInfo.getId());
    		String original_pwd = request.getParameter("original_pwd");
    		String pwd = request.getParameter("pwd");
    		
    		if(!CommonsUtil.getMD5(original_pwd).equals(user.getPassword())){
    			this.addActionMessage("您输入的原密码不正确，请重新输入。");
    			return INPUT;
    		}else{
    			user.setPassword(CommonsUtil.getMD5(pwd));
        		userManager.save(user);
        		this.userInfo = user;
        		
        		this.addActionMessage("修改密码成功。");
        		
    			LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyInformation, "修改密码成功");
    			logInfoManager.writeLog(logInfo);
    		}
    	}
		
		return "changePassword";
	}
	
	/**
	 *@Todo:修改补充资料
	 *@CreateTime:2011-8-29 上午11:47:09
	 * @return
	 */
	public String modifyAdditionInformation(){
		if(this.userInfo != null){
    		User  user = userManager.get(userInfo.getId());
    		
    		String companyName = request.getParameter("companyName");
    		String userType = request.getParameter("userType");
    		String yyzh = request.getParameter("yyzh");
    		String idCard = request.getParameter("idCard");
    		String address = request.getParameter("address");
    		String zipCode = request.getParameter("zipCode");
    		String contact = request.getParameter("contact");
    		String tel = request.getParameter("tel");
    		String emailAddress = request.getParameter("emailAddress");
    		String account = request.getParameter("account");
    		String bank = request.getParameter("bank");
    		String account_number = request.getParameter("account_number");
    		String provinceInfo = request.getParameter("province");
    		String cityInfo = request.getParameter("city");
    		
			user.setCompanyName(companyName);
			user.setUserType(userType);
			user.setYyzh(yyzh);
			user.setIdCard(idCard);
			user.setAddress(address);
			user.setZipCode(zipCode);
			user.setContact(contact);
			user.setTel(tel);
			user.setEmailAddress(emailAddress);
			user.setAccount(account);
			user.setBank(bank);
			user.setAccount_number(account_number);
    		
			if( provinceInfo != null ){
				if(StringUtil.isDigit(provinceInfo)){
					ProvinceInfo p = provinceInfoManager.get(Long.valueOf(provinceInfo));
					user.setProvinceInfo(p);
				}
			}
			
			if(cityInfo != null ){
				if(StringUtil.isDigit(cityInfo)){
					CityInfo  c = cityInfoManager.get(Long.valueOf(cityInfo));
					user.setCityInfo(c);
				}
			}
    		
    		userManager.save(user);
    		
    		this.userInfo = user;
    		
			LogInfo logInfo = buildLogInfo(LogTypeEnum.modifyInformation, "修改会员资料成功");
			logInfoManager.writeLog(logInfo);
    	}
		return "modifyAdditionInformation";
	}
	
	/**
	 * 登录验证
	 * @throws IOException 
	 * @throws ServletException 
	 */
	 @SuppressWarnings("unchecked")
	public String login() throws Exception {
		
			String username = request.getParameter("j_username");
			String password = request.getParameter("j_password");
			String captcha_parameter = request.getParameter("_captcha_parameter");
			String login_type = request.getParameter("login_type"); //登录类型,从登录窗口登录还是注册后直接登录(1表示注册后直接登录) 
			Object check_code  = session.getAttribute("check_code");
			
			if(login_type != null && "1".equals(login_type) ){
				
				password = (String) session.getAttribute(Constants.PassWord_Original);
				
				Object obj =  session.getAttribute(Constants.RegisterInformation);
				if(obj != null){
					User u = (User) obj;
					username = u.getUsername(); 
				}
				
			}else{
				if(check_code == null || ! captcha_parameter.equals((String)check_code)){
					request.setAttribute("errormessge", "验证码错误");
					return "login";
				}
			}
			
			List<User> userlist = userManager.findBy("username",username);
			if (userlist == null || userlist.size() == 0) {
				request.setAttribute("errormessge", "该用户不存在");
				return "login";
			}
			
			User user = userlist.get(0);
			UserState userState =user.getUserState();
			if(userState != null && (Constants.User_State_Normal).equals(userState.getEnglish_name())){
				if(user.getPassword().equals(CommonsUtil.getMD5(password))){
				}
				else{
					request.setAttribute("errormessge", "密码不正确");
					return "login";
				}
			}
			else{
				request.setAttribute("errormessge", "用户状态不正常");
				return "login";
		   }
			
          	List<Menu>  menuList = menuManager.loadMenusByUser(user.getId());
          	session.setAttribute(Constants.Userinfo, user);
            Map<String,Menu> map =  convertToMap(menuList);
            session.setAttribute(Constants.MenuMap, map);
			
     		PaintingManager paintingManager =  SpringContextHolder.getBean("paintingManager");
    		
            Page page = paintingManager.findPaintings("1",curPage, 6);//客座画家最新作品 
			List<Painting> paintingListOfGallery = (List<Painting>) page.getResult();
            
            page = userManager.findAvailableUser(curPage,12);
            List<User> userList = (List<User>) page.getResult();
            
            request.setAttribute("paintingListOfGallery", paintingListOfGallery);
            request.setAttribute("userList", userList);
            
			LogInfo logInfo = buildLogInfo(LogTypeEnum.Login, "登录成功");
			logInfo.setUserName(user.getUsername());
			logInfo.setUserCode(String.valueOf(user.getId()));
			logInfoManager.writeLog(logInfo);
		
			return SUCCESS;
	}
	
	/**
	* @Description: 退出
	* @param @throws Exception
	* @return String
	* @throws
	 */
	public String logout() throws Exception {
		session.invalidate();
		return SUCCESS;
	}
	
	private Map<String,Menu> convertToMap(List<Menu> menuList){
		Map<String,Menu> map = new HashMap<String,Menu>();
		for (Menu menu : menuList) {
			if(menu != null){
				map.put(menu.getName(), menu);
			}
		}
		return map;
	}

}
